package com.cbgolf.oa.views;

import android.app.Activity;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutParams;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.recycle.CommonAdapter;
import com.cbgolf.oa.adapter.recycle.ViewHolder;
import com.cbgolf.oa.base.BaseViewNew;
import com.cbgolf.oa.contract.IPlayerCaddieCarDetailsContract.IPlayerCaddieCarDetailsView;
import com.cbgolf.oa.contract.IPlayerCaddieCarDetailsContract.IPlayerCaddieCarDetailsWaiter;
import com.cbgolf.oa.entity.LatLon;
import com.cbgolf.oa.entity.ListBean;
import com.cbgolf.oa.entity.ParkBean;
import com.cbgolf.oa.entity.PlayerBean;
import com.cbgolf.oa.entity.StatisticsBean;
import com.cbgolf.oa.entity.StatisticsInfo;
import com.cbgolf.oa.entity.TeeTimeBean;
import com.cbgolf.oa.event.EventPark;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.manager.PopManager;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.CollectionUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.DensityUtil;
import com.cbgolf.oa.util.ErrorUtil;
import com.cbgolf.oa.util.ScreenUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.TypeUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.widget.RecyclerItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lq
 */
public class PlayerCaddieCarDetailsViewImp extends BaseViewNew
    implements IPlayerCaddieCarDetailsView {

  @BindView(R.id.topBack_ll)
  View topBack;
  @BindView(R.id.title_tv)
  TextView titleTv;
  /**
   * filterbar
   */
  @BindView(R.id.ll_filter_layout_bar)
  View filterBar;
  @BindView(R.id.ll_filter_teetime_layout)
  View regNoRegView;
  @BindView(R.id.ll_filter)
  View filterView;
  @BindView(R.id.tv_filter)
  TextView filterTv;

  @BindView(R.id.tv_reg)
  TextView regTv;
  @BindView(R.id.tv_noreg)
  TextView noRegTv;


  /**
   * body
   */
  @BindView(R.id.refresh)
  SmartRefreshLayout refreshLayout;
  @BindView(R.id.recycleView)
  RecyclerView recyclerView;

  private ErrorView errorView;

  private IPlayerCaddieCarDetailsWaiter worker;
  /**
   * 对应不同的统计类别，展示不同数据
   */
  private int mType;

  private CommonAdapter<StatisticsBean> adapter;
  private CommonAdapter<PlayerBean> playerAdapter;
  private CommonAdapter<TeeTimeBean> teeTimeAdapter;
  private List<StatisticsBean> listData = new ArrayList<>();
  private List<PlayerBean> listPlayers = new ArrayList<>();
  private List<TeeTimeBean> listTeetime = new ArrayList<>();
  private Map<Integer, Boolean> stateMap = new ArrayMap<>();
  private String[] teetimeFilter = new String[]{
      "今日", "明日"
  };
  private long[] teetimeFilterDate = new long[]{
      System.currentTimeMillis(), System.currentTimeMillis() + DateUtil.getOneDay()
  };
  /**
   * 筛选数据
   */
  private List<ListBean> listFilter = new ArrayList<>();
  private final int TEETIME_PERSON_NUM = 4;

  private int columNum = 5;

  public PlayerCaddieCarDetailsViewImp(Activity act, IPlayerCaddieCarDetailsWaiter waiter,
      int type) {
    this.worker = waiter;
    this.mType = type;

    ButterKnife.bind(this, act);
    super.init(act);
  }

  @Override
  protected void setViews() {
    ViewUtils.setText(titleTv, worker.getActivityTitle());
    ViewUtils.setRefreshCircleHeader(context, refreshLayout);
    errorView = new ErrorView(context);
    refreshLayout.setEnableLoadmore(false);
    refreshLayout.setEnableRefresh(false);
    if (mType == DataManager.STATISTICS_CAR_USING) {
      columNum = 4;
    }
    setlistAdapter();

  }

  /**
   * 在场人数adapter
   */
  private void setListPlayerAdapter() {
    if (null == listPlayers) {
      listPlayers = new ArrayList<>();
    }
    playerAdapter = new CommonAdapter<PlayerBean>(context,
        R.layout.item_rcy_parkmap_statistics_first,
        listPlayers) {
      @Override
      protected void convert(ViewHolder holder, PlayerBean bean, int position) {
        if (null == bean) {
          return;
        }
        if (bean.isNoData && listData.size() == 1) {
          holder.setVisible(R.id.layout, false)
              .setVisible(R.id.g_error_ll, true)
              .setText(R.id.g_error_tv, TextUtil.Text(bean.errorMsg))
              .setImageResource(R.id.g_error_logo_iv, ErrorView.getLogoRes(bean.errorCode));
          ViewUtils.setLayoutParams(holder.getView(R.id.g_error_layout_ll), ScreenUtil.getWidth(),
              ScreenUtil.getHeight() - DensityUtil.dip2px(context, 96));
          return;
        }
        holder.setVisible(R.id.g_error_ll, false)
            .setVisible(R.id.layout, true)
            .setText(R.id.tv_item_parkmap_first_info,
                new StringBuilder().append(TextUtil.Text(bean.fairwayName))
                    .append("(共")
                    .append(bean.personNum)
                    .append("人)").toString())
            .setImageResource(R.id.iv_item_parkmap_first_arrow,
                CollectionUtil.getMapBoolean(stateMap, position) ? R.mipmap.arrow_right_grey
                    : R.mipmap.arrow_down_grey)
            .setOnClickListener(R.id.ll_item_parkmap_first_bar, v -> {
//              if (Util.listIsNull(bean.listAllPerson)
//                  || bean.listAllPerson.size() <= 1) {
//                return;
//              }
              stateMap.put(position, !CollectionUtil.getMapBoolean(stateMap, position));
              playerAdapter.notifyDataSetChanged();
            });
        ViewUtils.setLayoutParams(holder.getView(R.id.rcy_item_parkmap), ScreenUtil.getWidth(),
            !CollectionUtil.getMapBoolean(stateMap, position) ? LayoutParams.WRAP_CONTENT :
//                DensityUtil.dip2px(context, 118));
                DensityUtil.dip2px(context, 0));
        setPlayerIconAdapter(holder.getView(R.id.rcy_item_parkmap), bean.listAllPerson);
      }
    };
    LinearLayoutManager lm = new LinearLayoutManager(context);
    lm.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(lm);
    recyclerView.addItemDecoration(new RecyclerItemDecoration(DensityUtil.dip2px(context, 5),
        0, 0, 0));
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(playerAdapter);
  }

  private void setPlayerIconAdapter(RecyclerView rcyView, List<List<LatLon>> list) {
    if (null == rcyView || Util.listIsNull(list)) {
      return;
    }
    CommonAdapter<List<LatLon>> adapter = new CommonAdapter<List<LatLon>>(context,
        R.layout.include_recycleview, list) {
      @Override
      protected void convert(ViewHolder holder, List<LatLon> list, int position) {
        if (Util.listIsNull(list)) {
          return;
        }
        setPlayerIconLastAdapter(holder.getView(R.id.recycleView), list);

      }
    };
    rcyView.setHasFixedSize(true);
    LinearLayoutManager gm = new LinearLayoutManager(context);
    gm.setOrientation(LinearLayoutManager.VERTICAL);
    rcyView.setLayoutManager(gm);
    rcyView.setAdapter(adapter);

  }

  private void setPlayerIconLastAdapter(RecyclerView rcyView, List<LatLon> list) {
    if (null == rcyView || Util.listIsNull(list)) {
      return;
    }
    CommonAdapter<LatLon> adapter = new CommonAdapter<LatLon>(context,
        R.layout.item_rcy_statistics_second, list) {
      @Override
      protected void convert(ViewHolder holder, LatLon latLon, int position) {
        if (null == latLon) {
          return;
        }
        int res = DataManager.isCaddie(latLon.identityType) ? R.mipmap.headportrait :
            R.mipmap.head_icon_xinjiang;
        holder.setImageResource(R.id.iv_item_rcy, res)
            .setText(R.id.tv_item_rcy, latLon.userName);
      }
    };
    rcyView.setHasFixedSize(true);
    GridLayoutManager gm = new GridLayoutManager(context, 5);
    rcyView.setLayoutManager(gm);
    rcyView.setAdapter(adapter);
  }


  @Override
  protected void setListener() {
    ViewUtils.setClick(topBack, v -> worker.back());
    ViewUtils.setClick(filterView, v -> {
      showFilter();
    });
  }

  private void showFilter() {

    PopManager.getInstance()
        .setWidth(ScreenUtil.getWidth() / 5)
        .setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
        .setAsView(filterView)
        .setItemlayout(R.layout.pop_item_tv)
        .setListData(listFilter)
        .setListWorker((id, name, position) -> {
          ViewUtils.setText(filterTv, name);
          worker.requestTeetimeData(id);
        })
        .showList(context);
  }

  private void setlistAdapter() {
    if (mType == DataManager.STATISTICS_PLAYER_REG_DETAILS) {
      ViewUtils.setVisible(regNoRegView, true);
      ViewUtils.setVisible(filterView, true);
      ViewUtils.setVisible(filterBar, true);
      ViewUtils.setText(filterTv, "今日");
      ListBean bean;
      listFilter.clear();
      for (int i = 0; i < teetimeFilter.length; i++) {
        bean = new ListBean();
        bean.nameForShow = teetimeFilter[i];
        bean.idForName = String.valueOf(teetimeFilterDate[i]);
        listFilter.add(bean);
      }
      setTeetimeAdapter();
    } else {
      setDefaulAdapter();
    }

  }

  /**
   * 公用adapter
   */
  private void setDefaulAdapter() {
    adapter = new CommonAdapter<StatisticsBean>(context, R.layout.item_rcy_parkmap_statistics_first,
        listData) {
      @Override
      protected void convert(ViewHolder holder, StatisticsBean bean, int position) {
        if (null == bean) {
          return;
        }
        if (bean.isNoData && listData.size() == 1) {
          holder.setVisible(R.id.layout, false)
              .setVisible(R.id.g_error_ll, true)
              .setText(R.id.g_error_tv, TextUtil.Text(bean.errorMsg))
              .setImageResource(R.id.g_error_logo_iv, ErrorView.getLogoRes(bean.errorCode));
          ViewUtils.setLayoutParams(holder.getView(R.id.g_error_layout_ll), ScreenUtil.getWidth(),
              ScreenUtil.getHeight() - DensityUtil.dip2px(context, 96));
          return;
        }
        String groupText = "";
        List<StatisticsInfo> listStatisticsInfo = null;
        switch (mType) {
          case DataManager.STATISTICS_PLAYER_IN_PARK:
            break;
          case DataManager.STATISTICS_CADDIE_IN_PARK:
            groupText = new StringBuilder()
                .append(TextUtil.Text(bean.levelName))
                .append("等级球僮")
                .toString();
            listStatisticsInfo = bean.caddieUsedInfo;
            break;
          case DataManager.STATISTICS_PLAYER_REG_DETAILS:

            break;
          case DataManager.STATISTICS_CAR_USING:
            groupText = bean.carTypeName;
            listStatisticsInfo = bean.courseCarUseInfo;
            break;
          default:
            break;
        }

        List<StatisticsInfo> finalListStatisticsInfo = listStatisticsInfo;
        holder.setVisible(R.id.g_error_ll, false)
            .setVisible(R.id.layout, true)
            .setText(R.id.tv_item_parkmap_first_info, TextUtil.Text(groupText))
            .setImageResource(R.id.iv_item_parkmap_first_arrow,
                CollectionUtil.getMapBoolean(stateMap, position) ? R.mipmap.arrow_right_grey
                    : R.mipmap.arrow_down_grey)
            .setOnClickListener(R.id.ll_item_parkmap_first_bar, v -> {
//              if (Util.listIsNull(finalListStatisticsInfo)
//                  || finalListStatisticsInfo.size() <= columNum) {
//                return;
//              }
              stateMap.put(position, !CollectionUtil.getMapBoolean(stateMap, position));
              adapter.notifyDataSetChanged();
            });
        ViewUtils.setLayoutParams(holder.getView(R.id.rcy_item_parkmap), ScreenUtil.getWidth(),
            !CollectionUtil.getMapBoolean(stateMap, position) ? LayoutParams.WRAP_CONTENT :
                DensityUtil.dip2px(context, 0));
//                DensityUtil.dip2px(context, 118));
        setDataAdapter(holder.getView(R.id.rcy_item_parkmap), listStatisticsInfo);

      }
    };
    LinearLayoutManager lm = new LinearLayoutManager(context);
    lm.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(lm);
    recyclerView.addItemDecoration(new RecyclerItemDecoration(DensityUtil.dip2px(context, 5),
        0, 0, 0));
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(adapter);
  }

  /**
   * teetime adapter
   */
  private void setTeetimeAdapter() {

    teeTimeAdapter = new CommonAdapter<TeeTimeBean>(context, R.layout.item_teetime, listTeetime) {
      @Override
      protected void convert(ViewHolder holder, TeeTimeBean bean, int position) {
        if (null == bean) {
          return;
        }
        if (bean.isNoData && listTeetime.size() == 1) {
          holder.setVisible(R.id.g_error_ll, true)
              .setVisible(R.id.layout, false)
              .setText(R.id.g_error_tv, TextUtil.Text(bean.errorMsg))
              .setImageResource(R.id.g_error_logo_iv, ErrorView.getLogoRes(bean.errorCode));
          ViewUtils.setLayoutParams(holder.getView(R.id.g_error_layout_ll), ScreenUtil.getWidth(),
              ScreenUtil.getHeight() - DensityUtil.dip2px(context, 96));
          return;
        }
        holder.setVisible(R.id.g_error_ll, false)
            .setVisible(R.id.layout, true)
            .setText(R.id.item_teetime_time_tv, DateUtil.stampToDateHm(bean.startTime));
        int regCount = TypeUtil.getInt(bean.recordCount);
        int noRegCount = TypeUtil.getInt(bean.noRecordCount);
        int hasNum = regCount + noRegCount;
        ImageView[] ivs = new ImageView[]{
            holder.getView(R.id.item_teetime_iv1),
            holder.getView(R.id.item_teetime_iv2),
            holder.getView(R.id.item_teetime_iv3),
            holder.getView(R.id.item_teetime_iv4)
        };

        if (position % 2 == 0) {
          holder.setVisible(R.id.left15, true);
          holder.setVisible(R.id.left5, true);
          holder.setVisible(R.id.right5, true);
          holder.setVisible(R.id.right15, false);
        } else {
          holder.setVisible(R.id.left5, true);
          holder.setVisible(R.id.left15, false);
          holder.setVisible(R.id.right5, true);
          holder.setVisible(R.id.right15, true);
        }
        holder.setVisible(R.id.bottom15, position == getItemCount() - 1);
        if (hasNum < TEETIME_PERSON_NUM) {
          for (int i = 0; i < TEETIME_PERSON_NUM; i++) {
            ViewUtils.setInVisible(ivs[i], i >= hasNum);
          }
        }
        for (int i = 0; i < TEETIME_PERSON_NUM; i++) {
          if (i < regCount) {
            ViewUtils.setImage(ivs[i], R.drawable.check);
          } else if (i < hasNum) {
            ViewUtils.setImage(ivs[i], R.drawable.nocheck);
          }
        }
      }
    };
    GridLayoutManager gm = new GridLayoutManager(context, 2);
    recyclerView.setLayoutManager(gm);
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(teeTimeAdapter);

  }

  /**
   * 二级adapter
   */
  private void setDataAdapter(RecyclerView rcyView, List<StatisticsInfo> list) {
    if (null == rcyView || Util.listIsNull(list)) {
      return;
    }
    CommonAdapter<StatisticsInfo> adapter = new CommonAdapter<StatisticsInfo>(context,
        R.layout.item_rcy_statistics_second, list) {
      @Override
      protected void convert(ViewHolder holder, StatisticsInfo bean, int position) {
        if (null == bean) {
          return;
        }
        String name = "";
        int res = 0;
        String headerUrl;
        switch (mType) {
          case DataManager.STATISTICS_PLAYER_IN_PARK:
            break;
          case DataManager.STATISTICS_CADDIE_IN_PARK:
            res = Util.isEquals(bean.usable, true) ? R.mipmap.head_icon_xinjiang
                : R.mipmap.head_xinjiang_grey;
            headerUrl = bean.headPic;
            name = Util.isEquals(bean.usable, true) ? new StringBuilder()
                .append(bean.caddieName)
                .append("(")
                .append(TextUtil.textNumInt(bean.customerCount))
                .append(")").toString()
                : bean.caddieName;
            break;
          case DataManager.STATISTICS_PLAYER_REG_DETAILS:

            break;
          case DataManager.STATISTICS_CAR_USING:
            name = new StringBuilder().append(TextUtil.Text(bean.carNumber))
                .append("号车(")
                .append(bean.usedCount)
                .append("/").append(getSeatNum(bean.seatNumber)).append(")").toString();
            if (TextUtil.contains(bean.carTypeName, "工作车")) {
              res = Util.isEquals(bean.carStatus, true) ? R.mipmap.car_work_on
                  : R.mipmap.car_work_off;
            } else if (TextUtil.contains(bean.carTypeName, "观光车")) {
              res = Util.isEquals(bean.carStatus, true) ? R.mipmap.car_xunchang_on
                  : R.mipmap.car_xunchang_off;
            } else {
              res = R.mipmap.car_xunchang_off;
            }
            break;
          default:
            break;
        }
        holder.setImageResource(R.id.iv_item_rcy, res)
            .setText(R.id.tv_item_rcy, name)
            .setOnClickListener(R.id.ll_item_rcy,
                v -> showDetailsPop(mType, new ParkBean.Builder()
                    .setStatisticsInfo(bean)
                    .build()));
      }
    };
    rcyView.setAdapter(adapter);
    rcyView.setHasFixedSize(true);
    GridLayoutManager gm = new GridLayoutManager(context,
        mType == DataManager.STATISTICS_CAR_USING ? 4 : 5);

    rcyView.setLayoutManager(gm);

  }

  /**
   * 球车座位数
   */
  private int getSeatNum(String seatNumber) {
    int res = 0;
    if (Util.isNull(seatNumber)) {
      return res;
    }
    switch (seatNumber) {
      case "SEAT_TWO":
        res = 2;
        break;
      case "SEAT_FOUR":
        res = 4;
        break;
      case "SEAT_SIX":
        res = 6;
        break;
      case "SEAT_EIGHT":
        res = 8;
        break;
      default:
        break;

    }
    return res;
  }

  /**
   * 详情pop
   */
  private void showDetailsPop(int type, ParkBean bean) {

    PopManager.getInstance().setWidth(ScreenUtil.getWidth() - DensityUtil.dip2px(context, 20))
        .setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
        .setType(type)
        .setParkBean(bean)
        .showParkMapCaddiePlayerWorker(context);

  }

  @Override
  public void showProgress() {
    if (refreshLayout.isRefreshing()
        || refreshLayout.isLoading()) {
      return;
    }
    AnimaUtil.showLoading(context);
  }

  @Override
  public void stopProgress() {
    AnimaUtil.stopLoading();
  }

  @Override
  public void requestFail(String msg, int code) {
    if (mType == DataManager.STATISTICS_PLAYER_REG_DETAILS
        || mType == DataManager.STATISTICS_PLAYER_IN_PARK) {
      if (null != errorView) {
        errorView.showError(refreshLayout, msg, code, null);
      }
    } else {
      listData.clear();
      listData.add(new StatisticsBean.Builder()
          .setIsNoData(true)
          .setError(msg, code)
          .build());
      adapter.notifyDataSetChanged();
    }

  }

  @Override
  public void requestOver(EventPark event) {
    stopProgress();
    if (null == event) {
      return;
    }
    switch (event.msgTarget) {
      case DataManager.STATISTICS_PLAYER_IN_PARK:

        break;
      case DataManager.STATISTICS_PLAYER_IN_PARK_PERSON_LIST:
        showPlayers(event.listPersons);
        break;
      case DataManager.STATISTICS_PLAYER_REG_DETAILS:
        if (Util.listIsNull(event.listTeetime)) {
          requestFail(event.errorMsg, event.errorCode);
          return;
        }
        if (null != errorView) {
          errorView.showData(refreshLayout);
        }
        listTeetime.clear();
        listTeetime.addAll(event.listTeetime);
        ViewUtils.setText(regTv, new StringBuilder()
            .append("已登记")
            .append(getRegNum())
            .append("人"));
        ViewUtils.setText(noRegTv, new StringBuilder()
            .append("未登记")
            .append(getNoRegNum())
            .append("人"));
        teeTimeAdapter.notifyDataSetChanged();

        break;
      case DataManager.STATISTICS_CADDIE_IN_PARK:
      case DataManager.STATISTICS_CAR_USING:
        if (Util.listIsNull(event.listStatistics)) {
          requestFail(event.errorMsg, event.errorCode);
          return;
        }
        listData.clear();
        listData.addAll(event.listStatistics);
        adapter.notifyDataSetChanged();
        break;
      default:
        break;
    }

  }

  /**
   * 已登记人数和
   */
  private int getRegNum() {
    int num = 0;
    for (int i = 0; i < listTeetime.size(); i++) {
      num += TypeUtil.getInt(listTeetime.get(i).recordCount);
    }
    return num;
  }

  /**
   * 未登记人数和
   */
  private int getNoRegNum() {
    int num = 0;
    for (int i = 0; i < listTeetime.size(); i++) {
      num += TypeUtil.getInt(listTeetime.get(i).noRecordCount);
    }
    return num;
  }

  /**
   * 展示 打球人在场 数据
   */
  @Override
  public void showPlayers(List<PlayerBean> list) {
    setListPlayerAdapter();
    if (Util.listIsNull(list)) {
      requestFail(ErrorUtil.NODATA, ErrorUtil.NODATA_CODE);
      return;
    }
    if (null != errorView) {
      errorView.showData(refreshLayout);
    }
    listPlayers.clear();
    listPlayers.addAll(list);
    playerAdapter.notifyDataSetChanged();

  }
}
